require("util/PrintUtil")
-- 初始化获取所有cousul上注册的所有服务和对应的ip 端口
local function handler(premature, ... )

    local http = require "resty.http";
    --JSON处理器
    local cjs = require "cjson.safe";


    local consulServiceStore = ngx.shared.consul_store

    --如果缓存创建失败
    if not consulServiceStore then
        ngx.log(ngx.ERR,"create consul service shared cache failed !");
        return
    end;

    local serversIpPort = {};

    local httpc, err = http:new();
    httpc:set_timeout(3000);

--  测试先写死
    local serviceName = 'cwifi-account-100-71-7-228-8003';

    --获取serviceName在consul注册的服务地址
    local consulServiceUrl = 'http://192.168.212.74:8500/v1/agent/service/'.. serviceName;
    local res, err= httpc:request_uri(
        consulServiceUrl,
        {
            keepalive_timeout = 2000 -- 毫秒
        }
    );
    --如果接口调用失败
    if not res then
        ngx.log(ngx.ERR,"router-filter call consul api failed  : ", err);
        return
    end;

    --解析JSON
    local obj = cjs.decode(res.body);

    --如果JSON解析失败
    if not obj then
        ngx.log(ngx.ERR,"router-filter parse consul api result failed  : ", res.body);
        return ngx.exit(500)
    end;

    serversIpPort[serviceName] = {obj['Address'],obj['Port'] }

    consulServiceStore:set('consulServiceUrlMap',cjs.encode(serversIpPort),60000);

    local consulServiceUrlMap = cjs.decode(consulServiceStore:get('consulServiceUrlMap'));

    httpc:close();

    if premature then
        return;
    end;

end


local ok , err = ngx.timer.at(1 , handler);